package com.toolbox.service.impl;

import com.toolbox.service.TranslationService;
import com.toolbox.utils.translate.TransApi;
import org.springframework.stereotype.Service;

import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class TranslationServiceImpl implements TranslationService {

    private static final String APP_ID = "20250927002465124";
    private static final String SECURITY_KEY = "LgSKaR3ei7FvKfZrdiXZ";

    // 模拟翻译实现，实际项目中可以集成第三方翻译API
    @Override
    public String translateText(String sourceText, String targetLanguage) {
        // 这里提供一个简单的模拟实现
        // 在实际项目中，应该调用真实的翻译API，如百度翻译API、谷歌翻译API等
        
        // 支持的目标语言
        String[] supportedLanguages = {"en", "zh"};
        boolean isSupported = false;
        for (String lang : supportedLanguages) {
            if (lang.equals(targetLanguage.toLowerCase())) {
                isSupported = true;
                break;
            }
        }
        
        if (!isSupported) {
            throw new IllegalArgumentException("不支持的目标语言: " + targetLanguage);
        }
        
        try {
            return callTranslationByBaidu(sourceText, targetLanguage);
        } catch (Exception e) {
            throw new RuntimeException("翻译过程中发生错误: " + e.getMessage(), e);
        }
    }

    /**
     *
     * @param sourceText
     * @param targetLanguage
     * @return
     * @throws IOException
     */
    private String callTranslationByBaidu(String sourceText, String targetLanguage) throws IOException {
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        String jsonResult = api.getTransResult(sourceText, "auto", targetLanguage);
        
        // 解析百度翻译API返回的JSON响应
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonResult);
            
            // 检查是否有错误
            if (jsonNode.has("error_code")) {
                String errorMsg = jsonNode.get("error_msg").asText();
                throw new RuntimeException("百度翻译API调用失败: " + errorMsg);
            }
            
            // 提取翻译结果
            JsonNode transResultArray = jsonNode.get("trans_result");
            if (transResultArray != null && transResultArray.isArray() && transResultArray.size() > 0) {
                JsonNode firstResult = transResultArray.get(0);
                return firstResult.get("dst").asText(); // dst字段包含翻译结果
            }
            
            return "翻译结果为空";
        } catch (Exception e) {
            throw new RuntimeException("解析翻译结果失败: " + e.getMessage(), e);
        }
    }
}